package cn.itcast.util;




import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.Map.Entry;
/**
 * @author : AdinZ  1454269@qq.com
 * @Project: xian-xian
 * @Package com.xianxian.utils
 * @Description: TODO
 * @date Date : 2019年05月24日 14:33
 **/

public class ExcelUtil {
    public static <T> void listToExcel(
            List<T> list,
            LinkedHashMap<String, String> fieldMap,
            String sheetName,
            int sheetSize,
            OutputStream out
    ) throws  Exception {

        if (list == null || list.size() == 0) {
            throw new Exception("");
        }
        if (sheetSize > 65535 || sheetSize < 1) {
            sheetSize = 65535;
        }
        WritableWorkbook wwb;
        try {
            wwb = Workbook.createWorkbook(out);
            double sheetNum = Math.ceil(list.size() / new Integer(sheetSize).doubleValue());
            for (int i = 0; i < sheetNum; i++) {
                if (1 == sheetNum) {
                    WritableSheet sheet = wwb.createSheet(sheetName, i);
                    fillSheet(sheet, list, fieldMap, 0, list.size() - 1);
                } else {
                    WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), i);
                    int firstIndex = i * sheetSize;
                    int lastIndex = (i + 1) * sheetSize - 1 > list.size() - 1 ? list.size() - 1 : (i + 1) * sheetSize - 1;
                    fillSheet(sheet, list, fieldMap, firstIndex, lastIndex);
                }
            }
            wwb.write();
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof Exception) {
                throw (Exception) e;
            } else {
                throw new Exception("导出Excel失败");
            }
        }

    }

    public static <T> void listToExcel(
            List<T> list,
            LinkedHashMap<String, String> fieldMap,
            String collectionName,
            String title,
            String content,
            String sheetName,
            int sheetSize,
            OutputStream out
    ) throws Exception {


        if (list == null || list.size() == 0) {
            throw new Exception("数据源中没有任何数据");
        }

        if (sheetSize > 65535 || sheetSize < 1) {
            sheetSize = 65535;
        }

        WritableWorkbook wwb;
        try {
            wwb = Workbook.createWorkbook(out);
            double sheetNum = Math.ceil(list.size() / new Integer(sheetSize).doubleValue());
            for (int i = 0; i < sheetNum; i++) {
                if (1 == sheetNum) {
                    WritableSheet sheet = wwb.createSheet(sheetName, i);
                    fillSheet(sheet, list, fieldMap, collectionName, title, content, 0, list.size() - 1);
                } else {
                    WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), i);
                    int firstIndex = i * sheetSize;
                    int lastIndex = (i + 1) * sheetSize - 1 > list.size() - 1 ? list.size() - 1 : (i + 1) * sheetSize - 1;
                    fillSheet(sheet, list, fieldMap, collectionName, title, content, firstIndex, lastIndex);
                }
            }

            wwb.write();
            wwb.close();

        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof Exception) {
                throw (Exception) e;
            } else {
                throw new Exception("导出Excel失败");
            }
        }

    }

    public static <T> void listToExcel(
            List<T> list,
            LinkedHashMap<String, String> fieldMap,
            String sheetName,
            OutputStream out
    ) throws Exception {

        listToExcel(list, fieldMap, sheetName, 65535, out);

    }

    //----------------------------------导出到流-END---------------------------------------------


    //----------------------------------导出到response-BEGIN---------------------------------------------


    /**
     * @param list      数据源
     * @param fieldMap  类的英文属性和Excel中的中文列名的对应关系
     * @param sheetName 工作表名称
     * @param sheetSize 每个工作表中记录的最大个数
     * @param response  使用response可以导出到浏览器
     * @param fileName  Excel的文件名
     * @throws Exception
     * @MethodName    : listToExcel
     * @Description    : 导出Excel（导出到浏览器，可以自定义工作表的大小）
     */
    public static <T> void listToExcel(
            List<T> list,
            LinkedHashMap<String, String> fieldMap,
            String sheetName,
            int sheetSize,
            HttpServletResponse response,
            String fileName
    ) throws Exception {

        if (TextUtils.isEmpty(fileName)) {
            fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new java.util.Date()).toString();
        }
        response.reset();
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("filename",fileName+".xls");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

        try {

            OutputStream out = response.getOutputStream();
            listToExcel(list, fieldMap, sheetName, sheetSize, out);

        } catch (Exception e) {
            e.printStackTrace();

                throw new Exception("导出Excel失败");

        }
    }

    /**
     * @param list           数据源
     * @param fieldMap       类的英文属性和Excel中的中文列名的对应关系
     * @param collectionName
     * @param title
     * @param content
     * @param sheetName
     * @param sheetSize      每个工作表中记录的最大个数
     * @param response       使用response可以导出到浏览器
     * @param fileName       Excel的文件名
     * @throws Exception
     * @MethodName    : listToExcel
     * @Description    : 导出Excel（导出到浏览器，可以自定义工作表的大小）
     */
    public static <T> void listToExcel(
            List<T> list,
            LinkedHashMap<String, String> fieldMap,
            String collectionName,
            String title,
            String content,
            String sheetName,
            int sheetSize,
            HttpServletResponse response,
            String fileName
    ) throws Exception {

        if (fileName == null || fileName.trim().equals("")) {
            fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new java.util.Date()).toString();
        }

        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
        try {

            OutputStream out = response.getOutputStream();
            listToExcel(list, fieldMap, collectionName, title, content, sheetName, sheetSize, out);

        } catch (Exception e) {
            e.printStackTrace();

            if (e instanceof Exception) {
                throw (Exception) e;
            } else {
                throw new Exception("导出Excel失败");
            }
        }
    }


    /**
     * @param list      数据源
     * @param fieldMap  类的英文属性和Excel中的中文列名的对应关系
     * @param sheetName 工作表的名称
     * @param sheetSize 每个工作表中记录的最大个数
     * @param response  使用response可以导出到浏览器
     * @throws Exception
     * @MethodName    : listToExcel
     * @Description    : 导出Excel（导出到浏览器，可以自定义工作表的大小）
     */
    public static <T> void listToExcel(
            List<T> list,
            LinkedHashMap<String, String> fieldMap,
            String sheetName,
            int sheetSize,
            HttpServletResponse response
    ) throws Exception {
        listToExcel(list, fieldMap, sheetName, sheetSize, response, "");
    }


    /**
     * @param list           数据源
     * @param fieldMap       类的英文属性和Excel中的中文列名的对应关系
     * @param collectionName
     * @param title
     * @param content
     * @param sheetName
     * @param response       使用response可以导出到浏览器
     * @throws Exception
     * @MethodName    : listToExcel
     * @Description    : 导出Excel（导出到浏览器，工作表的大小是2003支持的最大值）
     */
    public static <T> void listToExcel(
            List<T> list,
            LinkedHashMap<String, String> fieldMap,
            String collectionName,
            String title,
            String content,
            String sheetName,
            HttpServletResponse response
    ) throws Exception {

        listToExcel(list, fieldMap, collectionName, title, content, sheetName, 65535, response, "");
    }

    /**
     * @param list      数据源
     * @param fieldMap  类的英文属性和Excel中的中文列名的对应关系
     * @param sheetName 工作表名称
     * @param response  使用response可以导出到浏览器
     * @throws Exception
     * @MethodName    : listToExcel
     * @Description    : 导出Excel（导出到浏览器，工作表的大小是2003支持的最大值）
     */
    public static <T> void listToExcel(
            List<T> list,
            LinkedHashMap<String, String> fieldMap,
            String sheetName,
            HttpServletResponse response
    ) throws Exception {

        listToExcel(list, fieldMap, sheetName, 65535, response);
    }


    //----------------------------------导出到response-END---------------------------------------------

    //----------------------------------导入到list-BEGIN---------------------------------------------


    /**
     * @param in           ：承载着Excel的输入流
     * @param sheetName    ：要导入的工作表序号
     * @param entityClass  ：List中对象的类型（Excel中的每一行都要转化为该类型的对象）
     * @param fieldMap     ：Excel中的中文列头和类的英文属性的对应关系Map
     * @param uniqueFields ：指定业务主键组合（即复合主键），这些列的组合不能重复
     * @throws Exception
     * @MethodName            : excelToList
     * @Description                : 将Excel转化为List
     * @return                        ：List
     */
    public static <T> List<T> excelToList(
            InputStream in,
            String sheetName,
            Class<T> entityClass,
            LinkedHashMap<String, String> fieldMap,
            String[] uniqueFields
    ) throws Exception {
        List<T> resultList = new ArrayList<T>();
        try {
            Workbook wb = Workbook.getWorkbook(in);
            Sheet sheet = wb.getSheet(sheetName);
            int realRows = 0;
            for (int i = 0; i < sheet.getRows(); i++) {
                int nullCols = 0;
                for (int j = 0; j < sheet.getColumns(); j++) {
                    Cell currentCell = sheet.getCell(j, i);
                    if (currentCell == null || "".equals(currentCell.getContents().toString())) {
                        nullCols++;
                    }
                }
                if (nullCols == sheet.getColumns()) {
                    break;
                } else {
                    realRows++;
                }
            }
            if (realRows <= 1) {
                throw new Exception("Excel file not data");
            }
            Cell[] firstRow = sheet.getRow(0);

            String[] excelFieldNames = new String[firstRow.length];

            for (int i = 0; i < firstRow.length; i++) {
                excelFieldNames[i] = firstRow[i].getContents().toString().trim();
            }

            boolean isExist = true;
            List<String> excelFieldList = Arrays.asList(excelFieldNames);
            for (String cnName : fieldMap.keySet()) {
                if (!excelFieldList.contains(cnName)) {
                    isExist = false;
                    break;
                }
            }

            if (!isExist) {
                throw new Exception("Excel missing required fields, or field name is wrong");
            }


            LinkedHashMap<String, Integer> colMap = new LinkedHashMap<String, Integer>();
            for (int i = 0; i < excelFieldNames.length; i++) {
                colMap.put(excelFieldNames[i], firstRow[i].getColumn());
            }


            Cell[][] uniqueCells = new Cell[uniqueFields.length][];
            for (int i = 0; i < uniqueFields.length; i++) {
                int col = colMap.get(uniqueFields[i]);
                uniqueCells[i] = sheet.getColumn(col);
            }
            for (int i = 1; i < realRows; i++) {
                int nullCols = 0;
                for (int j = 0; j < uniqueFields.length; j++) {
                    String currentContent = uniqueCells[j][i].getContents();
                    Cell sameCell = sheet.findCell(currentContent,
                            uniqueCells[j][i].getColumn(),
                            uniqueCells[j][i].getRow() + 1,
                            uniqueCells[j][i].getColumn(),
                            uniqueCells[j][realRows - 1].getRow(),
                            true);
                    if (sameCell != null) {
                        nullCols++;
                    }
                }

                if (nullCols == uniqueFields.length) {
                    throw new Exception("There are duplicate rows in Excel, check");
                }
            }

            for (int i = 1; i < realRows; i++) {
                //新建要转换的对象
                T entity = entityClass.newInstance();
                for (Entry<String, String> entry : fieldMap.entrySet()) {
                    String cnNormalName = entry.getKey();
                    String enNormalName = entry.getValue();
                    int col = colMap.get(cnNormalName);
                    String content = sheet.getCell(col, i).getContents().toString().trim();
                    setFieldValueByName(enNormalName, content, entity);
                }

                resultList.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof Exception) {
                throw (Exception) e;
            } else {
                e.printStackTrace();
                throw new Exception("Importing Excel fails");
            }
        }
        return resultList;
    }

    //----------------------------------导入到list-END---------------------------------------------



    /*<-------------------------辅助的私有方法----------------------------------------------->*/

    /**
     * @param fieldName 字段名
     * @param o         对象
     * @MethodName    : getFieldValueByName
     * @Description    : 根据字段名获取字段值
     * @return 字段值
     */
    private static Object getFieldValueByName(String fieldName, Object o) throws Exception {

        Object value = null;
        Field field = getFieldByName(fieldName, o.getClass());

        if (field != null) {
            field.setAccessible(true);
            value = field.get(o);
        } else {
            Field[]  f=  o.getClass().getDeclaredFields();
            for(Field field1:f){
                if(field1.getName().equalsIgnoreCase("map"))
                    return fieldName;
            }

            throw new Exception(o.getClass().getSimpleName() + "Class field name does not exist " + fieldName);
        }

        return value;
    }

    /**
     * @param fieldName 字段名
     * @param clazz     包含该字段的类
     * @return 字段
     * @MethodName    : getFieldByName
     * @Description    : 根据字段名获取字段
     */
    private static Field getFieldByName(String fieldName, Class<?> clazz) {
        Field[] selfFields = clazz.getDeclaredFields();
        for (Field field : selfFields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz != null && superClazz != Object.class) {
            return getFieldByName(fieldName, superClazz);
        }
        return null;
    }


    /**
     * @param fieldNameSequence 带路径的属性名或简单属性名
     * @param o                 对象
     * @return 属性值
     * @throws Exception
     * @MethodName    : getFieldValueByNameSequence
     * @Description    : 根据带路径或不带路径的属性名获取属性值
     * 即接受简单属性名，如userName等，又接受带路径的属性名，如student.department.name等
     */
    private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception {

        Object value = null;

        Field[]  f=  o.getClass().getDeclaredFields();
        for(Field field1:f){
            if(field1.getName().equalsIgnoreCase("map"))
                return ((Map)o).get(fieldNameSequence);
        }


        String[] attributes = fieldNameSequence.split("\\.");
        if (attributes.length == 1) {
            value = getFieldValueByName(fieldNameSequence, o);
        } else {
            Object fieldObj = getFieldValueByName(attributes[0], o);
            String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1);
            value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
        }



        return value;

    }


    /**
     * @param fieldName  字段名
     * @param fieldValue 字段值
     * @param o          对象
     * @MethodName    : setFieldValueByName
     * @Description    : 根据字段名给对象的字段赋值
     */
    private static void setFieldValueByName(String fieldName, Object fieldValue, Object o) throws Exception {

        Field field = getFieldByName(fieldName, o.getClass());
        if (field != null) {
            field.setAccessible(true);
            Class<?> fieldType = field.getType();
            if (String.class == fieldType) {
                field.set(o, String.valueOf(fieldValue));
            } else if ((Integer.TYPE == fieldType)
                    || (Integer.class == fieldType)) {
                field.set(o, Integer.parseInt(fieldValue.toString()));
            } else if ((Long.TYPE == fieldType)
                    || (Long.class == fieldType)) {
                field.set(o, Long.valueOf(fieldValue.toString()));
            } else if ((Float.TYPE == fieldType)
                    || (Float.class == fieldType)) {
                field.set(o, Float.valueOf(fieldValue.toString()));
            } else if ((Short.TYPE == fieldType)
                    || (Short.class == fieldType)) {
                field.set(o, Short.valueOf(fieldValue.toString()));
            } else if ((Double.TYPE == fieldType)
                    || (Double.class == fieldType)) {
                field.set(o, Double.valueOf(fieldValue.toString()));
            } else if (Character.TYPE == fieldType) {
                if ((fieldValue != null) && (fieldValue.toString().length() > 0)) {
                    field.set(o, Character
                            .valueOf(fieldValue.toString().charAt(0)));
                }
            } else if (Date.class == fieldType) {
                field.set(o, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(fieldValue.toString()));
            } else {
                field.set(o, fieldValue);
            }
        } else {
            throw new Exception(o.getClass().getSimpleName() + "Class field name does not exist" + fieldName);
        }
    }


    /**
     * @param ws
     * @MethodName    : setColumnAutoSize
     * @Description    : 设置工作表自动列宽和首行加粗
     */
    private static void setColumnAutoSize(WritableSheet ws, int extraWith) {
        for (int i = 0; i < ws.getColumns(); i++) {
            int colWith = 0;
            for (int j = 0; j < ws.getRows(); j++) {
                String content = ws.getCell(i, j).getContents().toString();
                int cellWith = content.length();
                if (colWith < cellWith) {
                    colWith = cellWith;
                }
            }
            ws.setColumnView(i, colWith + extraWith);
        }

    }

    /**
     * @param sheet      工作表名称
     * @param list       数据源
     * @param fieldMap   中英文字段对应关系的Map
     * @param firstIndex 开始索引
     * @param lastIndex  结束索引
     * @MethodName    : fillSheet
     * @Description    : 向工作表中填充数据
     */
    private static <T> void fillSheet(
            WritableSheet sheet,
            List<T> list,
            LinkedHashMap<String, String> fieldMap,
            int firstIndex,
            int lastIndex
    ) throws Exception {

        String[] enFields = new String[fieldMap.size()];
        String[] cnFields = new String[fieldMap.size()];
        int count = 0;
        for (Entry<String, String> entry : fieldMap.entrySet()) {
            enFields[count] = entry.getKey();
            cnFields[count] = entry.getValue();
            count++;
        }
        for (int i = 0; i < cnFields.length; i++) {
            Label label = new Label(i, 0, cnFields[i]);
            sheet.addCell(label);
        }

        int rowNo = 1;
        for (int index = firstIndex; index <= lastIndex; index++) {
            T item = list.get(index);
            for (int i = 0; i < enFields.length; i++) {
                item.getClass().getDeclaredFields();
                Object objValue = getFieldValueByNameSequence(enFields[i], item);
                String fieldValue = objValue == null ? "" : objValue.toString();
                Label label = new Label(i, rowNo, fieldValue);
                sheet.addCell(label);
            }

            rowNo++;
        }

        setColumnAutoSize(sheet, 5);
    }

    /**
     * @param sheet               工作表名称
     * @param list                数据源
     * @param normalFieldMap      普通中英文字段对应关系的Map
     * @param collectionFieldName 集合類中英文字段对应关系的Map
     * @param collectionFieldName 集合類中英文字段对应关系的Map
     * @param firstIndex          开始索引
     * @param lastIndex           结束索引
     * @MethodName    : fillSheet
     * @Description    : 向工作表中填充数据
     */
    private static <T> void fillSheet(
            WritableSheet sheet,
            List<T> list,
            LinkedHashMap<String, String> normalFieldMap,
            String collectionFieldName,
            String title,
            String content,
            int firstIndex,
            int lastIndex
    ) throws Exception {

        String[] enFields = new String[normalFieldMap.size()];
        String[] cnFields = new String[normalFieldMap.size()];

        int count = 0;
        for (Entry<String, String> entry : normalFieldMap.entrySet()) {
            enFields[count] = entry.getKey();
            cnFields[count] = entry.getValue();
            count++;
        }


        for (int i = 0; i < cnFields.length; i++) {
            Label label = new Label(i, 0, cnFields[i]);
            sheet.addCell(label);
        }

        T firstItem = list.get(0);
        List childList = (List) getFieldValueByName(collectionFieldName, firstItem);

        int colCount = cnFields.length;
        for (Object obj : childList) {
            Object objValue = getFieldValueByNameSequence(title, obj);
            String fieldValue = objValue == null ? "" : objValue.toString();
            Label label = new Label(colCount, 0, fieldValue);
            sheet.addCell(label);
            colCount++;
        }

        int rowNo = 1;
        for (int index = firstIndex; index <= lastIndex; index++) {
            T item = list.get(index);
            for (int i = 0; i < enFields.length; i++) {
                Object objValue = getFieldValueByNameSequence(enFields[i], item);
                String fieldValue = objValue == null ? "" : objValue.toString();
                Label label = new Label(i, rowNo, fieldValue);
                sheet.addCell(label);
            }

            if (collectionFieldName != null && !collectionFieldName.equals("")) {
                List currentList = (List) getFieldValueByName(collectionFieldName, item);
                for (int i = 0; i < currentList.size(); i++) {
                    Object objValue = getFieldValueByNameSequence(content, currentList.get(i));
                    String fieldValue = objValue == null ? "" : objValue.toString();
                    Label label = new Label(i + cnFields.length, rowNo, fieldValue);
                    sheet.addCell(label);
                }
            }

            rowNo++;
        }

        setColumnAutoSize(sheet, 5);
    }
}
